﻿using CalligraphyEditor.CalligraphyData;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace CalligraphyEditor.ViewModel
{
    public class VMStelePapers
    {
        private CollectionViewSource _cvs;

        public CollectionViewSource Cvs
        {
            get { return _cvs; }
        }

        private ObservableCollection<T_StelePaper> _ocl;

        private T_Author _author;

        public VMStelePapers(T_Author a)
        {
            var q = from sp in CalligraphyEditor.App.Entities.T_StelePaper.Expand("T_Photo").Expand("T_Author") where  sp.AuthorID == a.ID &&  (sp.IsDeleted == null || sp.IsDeleted == false) select sp;
            _ocl = new ObservableCollection<T_StelePaper>(q);
            _cvs = new CollectionViewSource();
            _cvs.Source = _ocl;
            _author = a;
        }

        public void Save()
        {
            if (_cvs.View.CurrentItem == null)
                return;
            CalligraphyEditor.App.Entities.UpdateObject(_cvs.View.CurrentItem);
            CalligraphyEditor.App.Entities.SaveChanges();
        }

        public bool UploadPhoto()
        {
            var photo = PhotoHelper.BrowserAndUploadPhoto();
            if (photo != null)
            {
                T_StelePaper sp = _cvs.View.CurrentItem as T_StelePaper;
                sp.PhotoID = photo.ID;
                sp.T_Photo = photo;
                photo.T_StelePaper.Add(sp);
                CalligraphyEditor.App.Entities.UpdateObject(sp);
                CalligraphyEditor.App.Entities.SaveChanges();
                return true;
            }
            return false;
        }

        public void Add(bool isPaper)
        {
            T_StelePaper sp = new T_StelePaper();
            sp.Name = "碑帖";
            sp.T_Author = _author;
            sp.AuthorID = _author.ID;
            sp.IsPaper = isPaper;
            CalligraphyEditor.App.Entities.AddToT_StelePaper(sp);
            CalligraphyEditor.App.Entities.SaveChanges();
            _ocl.Add(sp);
        }

        public void Deleted()
        {
            T_StelePaper sp = _cvs.View.CurrentItem as T_StelePaper;
            sp.IsDeleted = true;
            CalligraphyEditor.App.Entities.UpdateObject(sp);
            CalligraphyEditor.App.Entities.SaveChanges();
            _ocl.Remove(sp);
        }
        
    }
}
